#!/bin/bash
# FRP 内网穿透自动化脚本 (支持服务端/客户端部署)
# 版本: v1.2
# 参数配置 (部署前请修改!)
# ----------------------------------------
FRP_VERSION="0.62.1"           # FRP 版本
ARCH="amd64"                   # 架构类型 (amd64/arm64/armv7)
SERVER_IP="101.34.57.65"     # 公网服务器 IP
TOKEN="123465"         # 认证令牌
DEFAULT_REMOTE_PORT=6001               # 公网暴露端口
# ----------------------------------------

# 颜色定义
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
RESET='\033[0m'

# 检查 root 权限
check_root() {
    if [ "$(id -u)" != "0" ]; then
        echo -e "${RED}错误: 此脚本需要 root 权限执行${RESET}"
        exit 1
    fi
}

# 安装依赖
install_deps() {
    echo -e "${BLUE}正在安装依赖: wget tar systemctl...${RESET}"
    if command -v apt &> /dev/null; then
        apt update -qq && apt install -y wget tar
    elif command -v yum &> /dev/null; then
        yum install -y wget tar
    else
        echo -e "${YELLOW}警告: 无法自动安装依赖，请手动安装 wget 和 tar${RESET}"
    fi
}

# 部署 FRP 服务端
deploy_server() {
    echo -e "${GREEN}正在部署 FRP 服务端...${RESET}"
    FRP_DIR="/opt/frp"
    mkdir -p $FRP_DIR && cd $FRP_DIR

    # 下载并解压 FRP
    if ! wget -q --show-progress "https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}/frp_${FRP_VERSION}_linux_${ARCH}.tar.gz"; then
        echo -e "${RED}错误: FRP 下载失败，请检查版本和网络连接${RESET}"
        exit 1
    fi
    tar -zxf frp_${FRP_VERSION}_linux_${ARCH}.tar.gz
    cd frp_${FRP_VERSION}_linux_${ARCH}

    # 生成 frps.toml
    cat > frps.toml <<EOF
bindPort = 7000
auth.token = "$TOKEN"
webServer.addr = "0.0.0.0"
webServer.port = 7500
webServer.user = "admin"
webServer.password = "admin123"
EOF

    # 创建 systemd 服务
    cat > /etc/systemd/system/frps.service <<EOF
[Unit]
Description=Frp Server Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$FRP_DIR/frp_${FRP_VERSION}_linux_${ARCH}
ExecStart=$FRP_DIR/frp_${FRP_VERSION}_linux_${ARCH}/frps -c frps.toml
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

    # 启动服务
    systemctl daemon-reload
    systemctl enable frps
    systemctl start frps

    # 防火墙规则
    if command -v ufw &> /dev/null; then
        ufw allow 7000/tcp
        ufw allow 7500/tcp
    fi

    echo -e "${GREEN}FRP 服务端部署完成!${RESET}"
    echo -e "管理面板: http://${SERVER_IP}:7500 (账号: admin 密码: admin123)"
}

# # 获取有效端口输入
# get_valid_port() {
#     local prompt="$1"
#     local default_port="$2"
#     while true; do
#         read -p "$prompt (默认: $default_port): " port
#         port=${port:-$default_port}
        
#         # 验证端口格式
#         echo "$port"
#         return
#     done
# }

# 部署 FRP 客户端
deploy_client() {
    # 交互获取远程端口
    read -p "请输入服务名称: " SSH_NAME
    read -p "请输入要暴露的远程端口 (默认: $DEFAULT_REMOTE_PORT): " REMOTE_PORT
    REMOTE_PORT=${REMOTE_PORT:-$DEFAULT_REMOTE_PORT}

    # Validate port number
    if ! echo "$REMOTE_PORT" | grep -Eq '^[0-9]+$' || [ "$REMOTE_PORT" -lt 1 ] || [ "$REMOTE_PORT" -gt 65535 ]; then
        echo -e "${RED}错误: 无效的端口号，使用默认端口 $DEFAULT_REMOTE_PORT${RESET}"
        REMOTE_PORT=$DEFAULT_REMOTE_PORT
    fi

    echo -e "${GREEN}正在部署 SSH...${RESET}"
    sudo apt update
    sudo apt install -y openssh-server
    sudo systemctl enable --now ssh
    
    # 后续客户端部署流程...
    echo -e "${GREEN}正在部署 FRP 客户端...${RESET}"
    FRP_DIR="/opt/frp"
    mkdir -p $FRP_DIR && cd $FRP_DIR

    # 下载并解压 FRP
    if ! wget -q --show-progress "https://github.com/fatedier/frp/releases/download/v${FRP_VERSION}/frp_${FRP_VERSION}_linux_${ARCH}.tar.gz"; then
        echo -e "${RED}错误: FRP 下载失败，请检查版本和网络连接${RESET}"
        exit 1
    fi
    tar -zxf frp_${FRP_VERSION}_linux_${ARCH}.tar.gz
    cd frp_${FRP_VERSION}_linux_${ARCH}

    # 生成 frpc.toml
    cat > frpc.toml <<EOF
serverAddr = "$SERVER_IP"
serverPort = 7000
auth.token = "$TOKEN"

[[proxies]]
name = "$SSH_NAME"
type = "tcp"
localIP = "127.0.0.1"
localPort = 22
remotePort = $REMOTE_PORT
EOF

    # 创建 systemd 服务
    cat > /etc/systemd/system/frpc.service <<EOF
[Unit]
Description=Frp Client Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$FRP_DIR/frp_${FRP_VERSION}_linux_${ARCH}
ExecStart=$FRP_DIR/frp_${FRP_VERSION}_linux_${ARCH}/frpc -c frpc.toml
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

    # 启动服务
    systemctl daemon-reload
    systemctl enable frpc
    systemctl start frpc

    echo -e "${GREEN}FRP 客户端部署完成!${RESET}"
    echo -e "SSH 连接命令: ${YELLOW}ssh -p $REMOTE_PORT your_user@$SERVER_IP${RESET}"
}

# 卸载 FRP
uninstall_frp() {
    echo -e "${YELLOW}正在卸载 FRP...${RESET}"
    systemctl stop frps frpc 2>/dev/null
    systemctl disable frps frpc 2>/dev/null
    rm -rf /etc/systemd/system/frp[cs].service
    rm -rf /opt/frp
    echo -e "${GREEN}FRP 已完全卸载${RESET}"
}

# 主菜单
main_menu() {
    clear
    echo -e "${BLUE}==================================="
    echo " FRP 内网穿透自动化部署脚本"
    echo "===================================${RESET}"
    echo "1. 部署 FRP 服务端 (公网服务器)"
    echo "2. 部署 FRP 客户端 (内网机器)"
    echo "3. 卸载 FRP"
    echo "4. 退出"
    read -p "请输入选项 [1-4]: " choice

    case $choice in
        1) check_root; install_deps; deploy_server ;;
        2) check_root; install_deps; deploy_client ;;
        3) check_root; uninstall_frp ;;
        4) exit 0 ;;
        *) echo -e "${RED}无效选项，请重新输入${RESET}"; sleep 1; main_menu ;;
    esac
}

# 启动主菜单
main_menu